import { ResultEnum } from '/@/enums/httpEnum';

import { useUserStore } from '/@/store/modules/user';

//const apiUrl = '/basic-api';
// const apiUrl = 'https://draw.laybg.com';
const apiUrl = 'http://houtai.2dc1l.com';

export class VRequest {
  private readonly options;

  constructor(options) {
    this.options;

    this.options = options;
  }

  get(config): Promise<any> {
    return this.request({ ...config, method: 'GET' });
  }

  post(config): Promise<any> {
    return this.request({ ...config, method: 'POST' });
  }

  put(config): Promise<any> {
    return this.request({ ...config, method: 'PUT' });
  }

  delete(config): Promise<any> {
    return this.request({ ...config, method: 'DELETE' });
  }

  request(config) {
    return new Promise((resolve, reject) => {
      const userStore = useUserStore();

      uni.request({
        ...config,
        header: Object.assign({}, config.header, {
          Token: userStore.getToken,
        }),
        url: apiUrl + config.url,
        success(res) {
          const { data } = res;
          const { code, msg } = data;
          if (
            config.url == '/region/getProvince' ||
            config.url == '/region/getCity' ||
            config.url == '/region/getDistrict' ||
            config.url == '/region/getStreet' ||
            config.url == '/api/draw/index' ||
            config.url == '/api/index/share' ||
            config.url == '/api/address/set' ||
            config.url == '/api/order/send'
          ) {
            return resolve(data);
          }
          const hasSuccess = data && Reflect.has(data, 'code') && code === ResultEnum.SUCCESS;

          if (hasSuccess) {
            return resolve(data.data);
          }

          if (code === '401') {
            userStore.logout();
          }

          uni.showToast({
            title: msg,
            icon: 'none',
          });
          reject(msg);
        },
        fail(err) {
          reject(err);
        },
      });
    });
  }
}

function createDefHttp(opt?) {
  return new VRequest(opt);
}

export const defHttp = createDefHttp();
